﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DigitalQuran.Collection {

    /// <summary>
    /// Represent Base for collection of History Items
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class HistoryCollectionBase<T> : List<T> {

        public HistoryCollectionBase() {
            Load();
        }

        /// <summary>
        /// Move to next item if possible
        /// </summary>
        /// <returns></returns>
        public T Next() {

            if (this.CurrentIndex < this.Count - 1)
                this.CurrentIndex++;

            return Current;
        }

        /// <summary>
        /// Move to previous item if possible
        /// </summary>
        /// <returns></returns>
        public T Previous() {

            if (this.CurrentIndex > 0)
                this.CurrentIndex--;

            return Current;
        }

        /// <summary>
        /// Gets current activated Item
        /// </summary>
        public T Current {
            get {
                if (this.Count > 0)
                    return this[CurrentIndex];

                return default(T);
            }
        }

        /// <summary>
        /// Get Index of active item
        /// </summary>
        public int CurrentIndex { get; private set; }

        internal abstract void Load();

        internal abstract void Save();
    }

    /// <summary>
    /// Represent Collection of Bookmarks
    /// </summary>
    public class BookmarkCollection : HistoryCollectionBase<Bookmark> {


        /* Bookmark Colletion Table Stream Sequence
         * 
         *  - Count (Int32)
         *  (LOOP)
         *      - Bookmark             
         */

        internal override void Load() {

            string filename = DigitalQuranDirectories.Configurations + "Bookmarks.bin";
            if (File.Exists(filename))
                using (var stream = new FileStream(filename, FileMode.Open))
                using (var reader = new BinaryReader(stream)) {
                    int max = reader.ReadInt32();
                    base.Capacity = max;
                    for (int i = 0; i < max; i++) {
                        this.Add(Bookmark.LoadFromStream(reader));
                    }
                }
        }

        internal override void Save() {

            using (var stream = new FileStream(DigitalQuranDirectories.Configurations + "Bookmarks.bin", FileMode.Create))
            using (var writer = new BinaryWriter(stream)) {
                writer.Write(this.Count);

                foreach (var item in this) {
                    Bookmark.SaveToStream(item, writer);
                }
            }
        }
    }
}